// 用户资料页面服务逻辑

import type { UserProfile, ProfileForm } from './types'

const API_BASE_URL = 'http://localhost:3000/api'

// 获取用户资料
export const fetchProfile = async (): Promise<UserProfile> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/profile`, {
    headers: token ? { Authorization: `Bearer ${token}` } : {}
  })

  if (res.ok) {
    return await res.json()
  }

  return {}
}

// 更新用户资料
export const updateProfile = async (form: ProfileForm): Promise<void> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/profile`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    },
    body: JSON.stringify(form)
  })

  if (!res.ok) {
    const err = await res.json()
    throw new Error(err.message || '更新失败')
  }
}

// 上传头像
export const uploadAvatar = async (file: File): Promise<string> => {
  const token = localStorage.getItem('token')
  const formData = new FormData()
  formData.append('avatar', file)

  const res = await fetch(`${API_BASE_URL}/upload/avatar`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${token}` },
    body: formData
  })

  if (!res.ok) {
    throw new Error('头像上传失败')
  }

  const data = await res.json()
  return data.url
}

// 获取头像URL
export const getAvatarUrl = (url?: string): string => {
  if (!url) return 'https://picsum.photos/200/200?random=avatar'
  if (/^https?:/.test(url)) return url
  return `${API_BASE_URL}${url}`
} 